package com.jiankang.askhealth.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.jdbc.UncategorizedSQLException;

import com.jiankang.askhealth.core.api.base.ApiBaseResultBean;
import com.jiankang.askhealth.core.api.base.ApiErrorResultBean;
import com.jiankang.askhealth.core.api.base.ApiResult;
import com.jiankang.askhealth.exception.ApiException;
import com.jiankang.askhealth.util.ApiErrorCode;
import com.jiankang.askhealth.util.ApiErrorMsgUtil;
import com.jiankang.askhealth.util.ApiThreadLocal;
import com.jiankang.askhealth.util.GsonUtil;
import com.jiankang.askhealth.util.StringUtils;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class ApiInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		String invoke = "";
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			String pageIndex = request.getParameter("pageIndex"); // 页码
			if (StringUtils.isNotBlank(pageIndex)
					&& !pageIndex.matches("^[1-9][0-9]*$")) {
				_printJsonResult(response,
						ApiErrorCode.BASE_ERROR_PAGEINDEX_NULL);
				return null;
			}
			String pageSize = request.getParameter("pageSize"); // 每页大小
			if (StringUtils.isNotBlank(pageSize)) {
				if (!pageSize.matches("^[1-9][0-9]*$")) {
					_printJsonResult(response,
							ApiErrorCode.BASE_ERROR_PAGESIZE_NULL);
					return null;
				}
				int pagesize = Integer.parseInt(pageSize);
				if (pagesize > 100) {
					_printJsonResult(response,
							ApiErrorCode.BASE_ERROR_PAGESIZE_NULL);
					return null;
				}
			}
			try {
				invoke = invocation.invoke();
			} catch (ApiException e) {
				_printJsonResult(response,
						new ApiErrorResultBean(e.getResult()));
				return null;
			}
			ApiResult result = ApiThreadLocal.getResultData().getResult();
			// 出错了
			if (result != null && !result.isSuccess()) {
				_printJsonResult(response, ApiThreadLocal.getResultData());
				return null;
			}
			result.setSuccess(true);
			ApiBaseResultBean resultObj = ApiThreadLocal.getResultData();
			_printJsonResult(response, resultObj);

		} catch (Exception e) {
			ApiResult result = _errorHandler(request,
					response, e);
			_printJsonResult(response, new ApiErrorResultBean(result));
		}
		return invoke;
	}

	private String _printJsonResult(HttpServletResponse response, int errorCode) {
		return _printJsonResult(response, new ApiErrorResultBean(new ApiResult(
				errorCode, ApiErrorMsgUtil.getErrorMsg(errorCode))),
				"yyyy-MM-dd");
	}

	private String _printJsonResult(HttpServletResponse response,
			ApiBaseResultBean o) {
		return _printJsonResult(response, o, "yyyy-MM-dd");
	}

	private String _printJsonResult(HttpServletResponse response,
			ApiBaseResultBean o, String dateFormat) {
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = null;
		String resultJson = GsonUtil.toJson(o, dateFormat);

		String jsonpCallback = ApiThreadLocal.getJsonpCallback();
		if (jsonpCallback != null) {
			resultJson = jsonpCallback + "(" + resultJson + ");";
		}

		try {
			out = response.getWriter();
			out.print(resultJson);
		} catch (IOException e) {
			response.setStatus(500);
		} finally {
			if (out != null) {
				out.flush();
				out.close();
				out = null;
			}
		}

		ApiResult result = o.getResult();
		return resultJson;
	}

	protected ApiResult _errorHandler(HttpServletRequest request,
			HttpServletResponse response, Exception e) {
		ApiResult result = new ApiResult(ApiErrorCode.RUNTIME_ERROR_BASE,
				ApiErrorMsgUtil.getErrorMsg(ApiErrorCode.RUNTIME_ERROR_BASE));
		if (e instanceof ApiException) {
			ApiException exception = (ApiException) e;
			ApiResult apiResult = exception.getResult();
			if (apiResult != null) {
				result = apiResult;
			}
		} else if (e instanceof UncategorizedSQLException) {
			if (e.getCause() != null
					&& (e.getCause().getCause() instanceof java.sql.DataTruncation)) {
				// content.overflow
			} else {
				// system.error
			}
		} else {
			// system.error
		}
		return result;
	}
}